package ar.edu.itba.it.pdc.httpParser.models;

import java.net.InetAddress;
import java.net.UnknownHostException;

import nl.bitwalker.useragentutils.UserAgent;

import ar.edu.itba.it.pdc.configuration.models.Request;
import ar.edu.itba.it.pdc.httpParser.interfaces.Model;

public class HttpRequest extends HttpMessage implements Request{

	HttpRequestLine initialLine;
	private InetAddress originIp;
	private InetAddress destinyIp;
	private String URI;
	private String OS;
	private String browser;
	
	public boolean isConnectionClose() {

		HttpVersion version = initialLine.getVersion();

		if (version == HttpVersion.ONE) {
			if (getHeaderValue("Connection") != null) {
				return getHeaderValue("Connection").toLowerCase().equals(
						"close");
			}
			return true;
		} else if (version == HttpVersion.ONEDOTONE) {

			if (getHeaderValue("Connection") != null) {
				return getHeaderValue("Connection").toLowerCase().equals(
						"close");
			}
			return false;
		}
		
		return true;
	}
	
	public boolean closeConnection(){
		return isConnectionClose();
	}

	@Override
	public Model getInitialLine() {
		return initialLine;
	}

	@Override
	public void setInitialLine(Model initialLine) {
		this.initialLine = (HttpRequestLine)initialLine;
		
	}

	@Override
	public String getOS() {
		if (OS == null) {
			UserAgent userAgent = new UserAgent(this.getHeaderValue("User-Agent"));
			OS = userAgent.getOperatingSystem().getName();
		}
		return OS;
	}

	@Override
	public InetAddress getDestinyIp() throws UnknownHostException {
		if (destinyIp == null) {
			destinyIp = InetAddress.getByName(this.getHeaderValue("Host"));
		}
		return destinyIp;
	}

	@Override
	public InetAddress getOriginIp() {
		return originIp;
	}

	@Override
	public String getURI() {
		if (URI == null) {
			URI = ((HttpRequestLine)this.getInitialLine()).getResource();
			if (URI.charAt(0) == '/') {
				URI = "http://" + this.getHeaderValue("Host") + URI;
			}
		}
		return URI;
	}

	@Override
	public String getBrowser() {
		if (browser == null) {
			UserAgent userAgent = new UserAgent(this.getHeaderValue("User-Agent"));
			browser = userAgent.getBrowser().getName();
		}
		return browser;
	}
	
	public void setOriginIp(InetAddress originIp) {
		this.originIp = originIp;
	}
	
	public void removeHostFromSource() {
		initialLine.removeHostFromSource();
		
	}
}
